<template>
  <div class="app-container">
    <!-- 查询条件 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
      <el-form-item label="优惠券名称" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入优惠券名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="优惠券ID" align="center" prop="id" />
      <el-table-column label="优惠券名称" align="center" prop="title" />
      <el-table-column label="优惠券编码" align="center" prop="coupon_code" />
      <el-table-column label="优惠券类型" align="center" prop="type" width="250px">
        <template #default="scope">
            <div v-if="scope.row.type==1" >
                    <el-tag>满减券(满{{  scope.row.min_amount}}减{{ scope.row.amount }})</el-tag>   
            </div>
            <div v-if="scope.row.type==2">
                    <el-tag>折扣券(折扣:{{scope.row.amount}})</el-tag>   
            </div>
            <div v-if="scope.row.type==3">
                    <el-tag>立减券(立减:{{ scope.row.amount }})</el-tag>   
            </div>
          <!-- <dict-tag :options="typeOptions" :value="scope.row.type"/> -->
        </template>
      </el-table-column>
      <el-table-column label="有效期类型" align="center" prop="valid_type" width="350px">
        <template #default="scope">
            <div v-if="scope.row.valid_type==2" >
                    <el-tag>领取后{{ scope.row.after_days }}天有效</el-tag>   
            </div>
            <div v-if="scope.row.valid_type==1">
                    <el-tag>固定有效期 {{ scope.row.valid_start_time ? formatTime(scope.row.valid_start_time) : '-' }} 至 {{ scope.row.valid_end_time ? formatTime(scope.row.valid_end_time) : '-' }}</el-tag>   
            </div>
            
          <!-- <dict-tag :options="validTypeOptions" :value="scope.row.valid_type"/> -->
        </template>
      </el-table-column>
      <!-- <el-table-column label="有效天数" align="center" prop="after_days" v-if="dataList.some(item => item.after_days)" />
      <el-table-column label="有效期开始" align="center" width="180">
        <template #default="scope">
          {{ scope.row.valid_start_time ? formatTime(scope.row.valid_start_time) : '-' }}
        </template>
      </el-table-column>
      <el-table-column label="有效期结束" align="center" width="180">
        <template #default="scope">
          {{ scope.row.valid_end_time ? formatTime(scope.row.valid_end_time) : '-' }}
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="每人限领" align="center" prop="limit_per_user" /> -->
      <el-table-column label="使用频率限制" align="center" width="200">
        <template #default="scope">
          {{ formatFrequencyLimit(scope.row.frequency_limit) }}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <!-- <dict-tag :options="statusOptions" :value="scope.row.status"/> -->
           <el-tag v-if="scope.row.status==1">启用</el-tag>
           <el-tag type="danger" v-if="scope.row.status==0">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="created_at" />
      <el-table-column label="更新时间" align="center" prop="updated_at" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            icon="Edit"
            link
            type="primary"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            link
            icon="Delete"
            type="primary"

            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改优惠券对话框 -->
    <el-dialog :title="title" v-model="open" width="35%" append-to-body draggable :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="优惠券名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入优惠券名称" />
        </el-form-item>
        <el-form-item label="优惠券类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择优惠券类型" @change="handleTypeChange">
            <el-option
              v-for="dict in typeOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      
        <!-- v-if="form.type == 2 || form.type == 3" -->
        <el-form-item  label="优惠金额" prop="amount">
          <el-input v-model="form.amount" placeholder="面值（折扣类型填写你的折扣(例如0.85),立减类型和满减直接填入优惠数字(例如5))即可） 示例值 5.00 / 0.85" />
        </el-form-item>
        <el-form-item v-if="form.type == 1" label="最低消费金额" prop="min_amount">
          <el-input v-model="form.min_amount" placeholder="请输入最低消费金额" />
        </el-form-item>
        <el-form-item label="有效期类型" prop="valid_type">
          <el-select v-model="form.valid_type" placeholder="请选择有效期类型" @change="handleValidTypeChange">
            <el-option
              v-for="dict in validTypeOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.valid_type == 2" label="有效天数" prop="after_days">
          <el-input v-model="form.after_days" placeholder="请输入有效天数" />
        </el-form-item>
        <el-form-item v-if="form.valid_type == 1" label="有效期开始时间" prop="valid_start_time">
          <el-date-picker
            v-model="form.valid_start_time"
            type="datetime"
            placeholder="选择开始时间"
            value-format="X"
          />
        </el-form-item>
        <el-form-item v-if="form.valid_type == 1" label="有效期结束时间" prop="valid_end_time">
          <el-date-picker
            v-model="form.valid_end_time"
            type="datetime"
            placeholder="选择结束时间"
            value-format="X"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="发放对象" prop="assign_type">
          <!-- -->
          <el-radio-group v-model="form.assign_type">
            <el-radio
              v-for="dict in assignTypeOptions"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="发放对象值" prop="assign_ids">
            <el-input
                v-model="form.assign_ids"
                :rows="5"
                type="textarea"
                placeholder="请输入发放对象值，多个用换行分隔"
            />
        </el-form-item>

      <!--<el-form-item label="每人限领数量" prop="limit_per_user">
          <el-input-number v-model="form.limit_per_user" :min="1" />
        </el-form-item>
        <el-form-item label="是否限制使用" prop="is_limit">
          <el-radio-group v-model="form.is_limit">
            <el-radio
              v-for="dict in isLimitOptions"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item 
          label="使用频率限制" 
          prop="frequency_limit"
          v-if="form.is_limit === 1"
        >
          <el-row :gutter="20">
            <el-col :span="8">
              <el-select v-model="form.frequency_type" placeholder="频率类型" style="width:100%">
                <el-option label="天" value="day" />
                <el-option label="周" value="week" />
                <el-option label="月" value="month" />
                <el-option label="年" value="year" />
              </el-select>
            </el-col>
            <el-col :span="8">
              <el-input-number 
                v-model="form.frequency_period" 
                :min="1" 
                placeholder="每N个周期"
                controls-position="right"
                style="width:100%"
              />
            </el-col>
            <el-col :span="8">
              <el-input-number 
                v-model="form.frequency_count" 
                :min="1" 
                placeholder="限制次数"
                controls-position="right"
                style="width:100%"
              />
            </el-col>
          </el-row>
        </el-form-item>
        -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm" :loading="isSubmitIng">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getList, add, change, del } from '@/api/platform/coupon'

export default {
  name: 'Coupon',
  data() {
    return {
        isSubmitIng:false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      dataList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: undefined
      },
      // 表单参数
      form: {
        frequency_type: 'day',
        frequency_period: 1,
        frequency_count: 1,
        assign_type:3
      },
      // 表单校验
      rules: {
        title: [{ required: true, message: '优惠券名称不能为空', trigger: 'blur' }],
        type: [{ required: true, message: '优惠券类型不能为空', trigger: 'change' }],
        valid_type: [{ required: true, message: '有效期类型不能为空', trigger: 'change' }],
        status: [{ required: true, message: '状态不能为空', trigger: 'change' }],
        limit_per_user: [{ required: true, message: '每人限领数量不能为空', trigger: 'blur' }],
        // amount: [{ required: true, message: '优惠金额不能为空', trigger: 'blur' }],
        frequency_type: [{ required: true, message: '请选择频率类型', trigger: 'change' }],
        frequency_period: [{ required: true, message: '请输入周期数', trigger: 'blur' }],
        frequency_count: [{ required: true, message: '请输入限制次数', trigger: 'blur' }],
        min_amount: [{ required: true, message: '最低消费金额不能为空', trigger: 'blur' }],
        amount: [{ required: true, message: '面值（折扣类型填写你的折扣(例如0.85),立减类型直接填入优惠数字(例如5))即可） 示例值 5.00 / 0.85', trigger: 'blur' }],
        after_days: [{ required: true, message: '有效天数不能为空', trigger: 'blur' }],
        valid_start_time: [{ required: true, message: '有效期开始时间不能为空', trigger: 'change' }],
        valid_end_time: [{ required: true, message: '有效期结束时间不能为空', trigger: 'change' }],
        is_limit: [{ required: true, message: '是否限制使用不能为空', trigger: 'change' }],
        assign_type: [{ required: true, message: '发放对象不能为空', trigger: 'change' }],
        // frequency_limit: [{ required: true, message: '使用频率限制不能为空', trigger: 'blur' }],
        assign_ids: [{ required: true, message: '发放对象值不能为空', trigger: 'blur' }]
      },
      // 字典
      typeOptions: [
        { value: 1, label: '满减券' },
        { value: 2, label: '折扣券' },
        { value: 3, label: '立减券(代金券)' }
      ],
      validTypeOptions: [
        { value: 1, label: '固定时间段' },
        { value: 2, label: '领取后N天有效' }
      ],
    //   0-禁用 1-启用 2-删除
      statusOptions: [
        { value: 0, label: '禁用' },
        { value: 1, label: '启用' },
        // { value: '2', label: '删除' }
      ],
      isLimitOptions: [
        { value: 0, label: '否' },
        { value: 1, label: '是' },
        // { value: '2', label: '删除' }
      ],
      assignTypeOptions:[
        // { value: 1, label: '全部用户' },
        // { value: 2, label: '指定用户ID' },
        { value: 3, label: '指定手机号' }
      ]
      
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 格式化时间戳
    formatTime(timestamp) {
      if (!timestamp) return '-'
      const date = new Date(timestamp * 1000)
      return date.toLocaleString()
    },
    // 格式化使用频率限制
    formatFrequencyLimit(jsonStr) {
      if (!jsonStr) return '-'
      try {
        const { frequency_type, frequency_period, frequency_count } = JSON.parse(jsonStr)
        const typeMap = { day: '天', week: '周', month: '月', year: '年' }
        return `每${frequency_period}${typeMap[frequency_type]}限用${frequency_count}次`
      } catch {
        return '-'
      }
    },
    /** 查询优惠券列表 */
    getList() {
      this.loading = true
      getList(this.queryParams).then(response => {
        this.dataList = response.data.items
        this.total = response.data.total
        this.loading = false
        console.log('表格数据:', this.dataList)
        console.log('字典选项:', {
          typeOptions: this.typeOptions,
          validTypeOptions: this.validTypeOptions,
          statusOptions: this.statusOptions
        })
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        title: undefined,
        type: undefined,
        valid_type: undefined,
        status: 1,
        assign_type: 3,
        limit_per_user: 1,
        frequency_type: 'day',
        frequency_period: 1,
        frequency_count: 1,
        min_amount: undefined,
        amount: undefined,
        after_days: undefined,
        valid_start_time: undefined,
        valid_end_time: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 优惠券类型变化
    handleTypeChange(value) {
      if (value == 1) {
        this.rules.min_amount[0].required = true
        this.rules.amount[0].required = false
      } else {
        this.rules.min_amount[0].required = false
        this.rules.amount[0].required = true
      }
    },
    // 有效期类型变化
    handleValidTypeChange(value) {
      if (value == 1) {
        this.rules.after_days[0].required = true
        this.rules.valid_start_time[0].required = false
        this.rules.valid_end_time[0].required = false
      } else {
        this.rules.after_days[0].required = false
        this.rules.valid_start_time[0].required = true
        this.rules.valid_end_time[0].required = true
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加优惠券'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
        console.log('修改按钮操作', row)
      this.reset()
      const id = row.id || this.ids
      // 模拟获取优惠券详情
      this.form = {
        ...row,
        is_limit: row.is_limit,
        ...(row.frequency_limit ? JSON.parse(row.frequency_limit) : {}),
        frequency_type: row.frequency_limit ? JSON.parse(row.frequency_limit).frequency_type : 'day',
        frequency_period: row.frequency_limit ? JSON.parse(row.frequency_limit).frequency_period : 1,
        frequency_count: row.frequency_limit ? JSON.parse(row.frequency_limit).frequency_count : 1,
        valid_start_time: row.valid_start_time ? parseInt(row.valid_start_time) : undefined,
        valid_end_time: row.valid_end_time ? parseInt(row.valid_end_time) : undefined
      }
      this.open = true
      this.title = '修改优惠券'
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          // 组装数据
          const formData = {
            ...this.form,
            frequency_limit: this.form.is_limit === 1
              ? JSON.stringify({
                    frequency_type: this.form.frequency_type,
                    frequency_period: this.form.frequency_period,
                    frequency_count: this.form.frequency_count
                })
              : null
          }
          this.isSubmitIng = true
          if (this.form.id != null) {
            change(formData).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            }).finally(() => {
              this.isSubmitIng = false
            })
          } else {
            add(formData).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            }).finally(() => {
              this.isSubmitIng = false
            })
          }
         
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除优惠券编号为"' + ids + '"的数据项？').then(function() {
        return del(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    }
  }
}
</script>